package com.leesche.zcsp.node.web.controller.web.v2.param;

import com.leesche.zcsp.node.net.service.NetService;
import com.leesche.zcsp.node.utils.web.SessionManager;
import com.leesche.zcsp.node.utils.web.filemanager.FileManager;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.controller.web.v2.admin.WebAdminController;
import com.leesche.zcsp.node.web.model.PubDevConfigParam;
import com.leesche.zcsp.node.web.model.PubDevSetParam;
import com.leesche.zcsp.node.web.model.PubDevice;
import com.leesche.zcsp.node.web.model.PubParamGroup;
import com.leesche.zcsp.node.web.service.PubDevConfigParamService;
import com.leesche.zcsp.node.web.service.PubDevSetParamService;
import com.leesche.zcsp.node.web.service.PubDeviceService;
import com.leesche.zcsp.node.web.service.PubParamGroupService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.Map;

/**
 * Created by kaider on 2017/1/11.
 */
@Controller
@RequestMapping("/v2/factory/param")
public class WebFactoryDeviceParamController extends WebAdminController {

    private final static Logger LOGGER = LoggerFactory.getLogger(WebFactoryDeviceParamController.class);

    @Autowired
    private PubParamGroupService groupService;
    @Autowired
    private PubDevConfigParamService configParamService;
    @Autowired
    private PubDevSetParamService paramService;
    @Autowired
    private PubDeviceService deviceService;
    @Autowired
    private NetService netService;

    /**
     * 添加参数组
     * @param typeName
     * @param groupName
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "addParamGroup", method = RequestMethod.POST)
    public Map<String,Object> addParamGroup(
        Long typeName,
        String groupName
    ){
        Long adminId = getFactoryAdminId();
        PubParamGroup paramGroup = new PubParamGroup();
        try{
            paramGroup.setAdminid(adminId);
            paramGroup.setDevicetypeid(typeName);
            paramGroup.setParamgroupname(groupName);
            paramGroup.setCreatetime(new Date());
            paramGroup.setUpdatetime(new Date());
            groupService.insert(paramGroup);
            return WebResult.success().put("groupId",paramGroup.getParamgroupid()).toMap();
        } catch (Exception e){
            LOGGER.error("PubParamGroup isnert",e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 添加参数设置
     * @param typeName
     * @param groupName
     * @param name
     * @param inVal
     * @param outVal
     * @param unit
     * @param defVal
     * @param remark
     * @param urlVal
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "addParam", method = RequestMethod.POST)
    public Map<String,Object> addParam(
        @RequestParam(value = "logo", required = false) MultipartFile file,
        Long typeName,Long groupName,String name,Integer inVal,Integer outVal,Integer commId,
        String unit,Integer defVal,String remark, String urlVal,String permissions,int isOperator
    ){
        Long adminId = getFactoryAdminId();
        String logo = "";
        if(file!=null){
            String logoPath = SessionManager.getContext().getRealPath("").replace(Constants.SITE_NAME, Constants.SYSTEM_TMAGE_DEVICE_PARAM_DIRECTORY);
            String logoSaveResult = FileManager.saveImage(file, logoPath);
            if(logoSaveResult.contains(FileManager.ERRORSTR)) {
                return WebResult.failure(logoSaveResult.replace(FileManager.ERRORSTR, "")).toMap();
            } else {
                logo = SessionManager.getWebServerURL() + Constants.SYSTEM_TMAGE_DEVICE_PARAM_DIRECTORY + "/" + logoSaveResult;
            }
        }

        PubDevConfigParam configParam = new PubDevConfigParam();
        configParam.setDevicetypeid(typeName);
        configParam.setParamgroupid(groupName);
        configParam.setDevparamname(name);
        if(configParamService.checkCommId(isOperator, typeName,commId)<1) {
            configParam.setCommid(commId);
        }else{
            return WebResult.failure("命令编号重复或超出范围!").toMap();
        }
        configParam.setIndevparamval(inVal);
        configParam.setOutdevparamval(outVal);
        configParam.setDevparamunit(unit);
        configParam.setDevparamdefval(defVal);
        configParam.setRemark(remark);
        configParam.setParamvidiourl(urlVal);
        configParam.setSdata2(permissions);
        configParam.setParamimageurl(logo);
        if(configParam.getParamgroupid()==null){
            return WebResult.failure("请选择参数组!").toMap();
        }
        if(StringUtils.isEmpty(configParam.getDevparamname())){
            return WebResult.failure("参数名称不能为空!").toMap();
        }
        configParam.setCreatetime(new Date());
        configParam.setUpdatetime(new Date());
        configParam.setAdminid(adminId);

        try{
            configParamService.insert(configParam);
            Long confParamId = configParam.getConfparamid();
            configParam = configParamService.selectByPrimaryKey(confParamId);
            Integer command = configParam.getCommid();
            return WebResult.success().put("command",command).put("logo",logo).put("confParamId",confParamId).toMap();
        }catch (Exception e){
            LOGGER.error("PubParamConfig insert",e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 修改参数设置
     * @param configParamId
     * @param typeName
     * @param groupName
     * @param name
     * @param inVal
     * @param outVal
     * @param unit
     * @param defVal
     * @param remark
     * @param urlVal
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "editParam", method = RequestMethod.POST)
    public Map<String,Object> editParam(
        @RequestParam(value = "logo", required = false) MultipartFile file,
        Long configParamId,Long typeName,Long groupName,String name,Integer inVal,Integer commId,int isOperator,
        Integer outVal,String unit,Integer defVal,String remark, String urlVal,String logoVal,String permissions

    ){
        PubDevConfigParam configParam=configParamService.selectByPrimaryKey(configParamId);
        Long adminId = getFactoryAdminId();
        if(configParam.getAdminid()!=null&&!configParam.getAdminid().equals(adminId)){
            return WebResult.failure("您无权限操作此参数").toMap();
        }
        if(groupName==null){
            return WebResult.failure("请选择参数组!").toMap();
        }
        if(StringUtils.isEmpty(name)){
            return WebResult.failure("参数名称不能为空!").toMap();
        }
        String logo ="";
        if(file!=null){
            String logoPath = SessionManager.getContext().getRealPath("").replace(Constants.SITE_NAME, Constants.SYSTEM_TMAGE_DEVICE_PARAM_DIRECTORY);
            String logoSaveResult = FileManager.saveImage(file, logoPath);
            if(logoSaveResult.contains(FileManager.ERRORSTR)) {
                return WebResult.failure(logoSaveResult.replace(FileManager.ERRORSTR, "")).toMap();
            } else {
                logo = SessionManager.getWebServerURL() + Constants.SYSTEM_TMAGE_DEVICE_PARAM_DIRECTORY + "/" + logoSaveResult;
            }
        }else{
            logo = logoVal;
        }
        configParam.setAdminid(adminId);
        configParam.setDevicetypeid(typeName);
        configParam.setParamgroupid(groupName);
        configParam.setDevparamname(name);

        if(!configParam.getCommid().equals(commId)){
            if(configParamService.checkCommId(isOperator, typeName,commId)<1) {
                configParam.setCommid(commId);
            }else{
                return WebResult.failure("命令编号重复或超出范围!").toMap();
            }
        }
        configParam.setIndevparamval(inVal);
        configParam.setOutdevparamval(outVal);
        configParam.setDevparamunit(unit);
        configParam.setDevparamdefval(defVal);
        configParam.setRemark(remark);
        configParam.setParamimageurl(logo);
        configParam.setParamvidiourl(urlVal);
        configParam.setSdata2(permissions);
        configParam.setCreatetime(new Date());
        configParam.setUpdatetime(new Date());

        try{
            configParamService.updateByPrimaryKey(configParam);
            return WebResult.success().put("logo",logo).toMap();
        }catch (Exception e){
            LOGGER.error("PubParamConfig update",e);
            return WebResult.failure(e).toMap();
        }
    }


    /**
     * 更改设备默认参数
     * @param paramId
     * @param paramVal
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "updateDeviceParam", method = RequestMethod.POST)
    public Map<String,Object> updateDeviceParam(
        Long paramId,
        Integer paramVal
    ){
        // Long adminId = getAdminId();
        try {
            PubDevSetParam devParam = paramService.selectByPrimaryKey(paramId);
            Integer command = devParam.getCommid();
            PubDevice device = deviceService.selectByPrimaryKey(devParam.getDeviceid());
            String imme = device.getImme();
            boolean flag = netService.sendClientSetParam(imme,command,paramVal);
            if(flag==false){
                LOGGER.error("netService.sendClientSetParam-->发送给阿里更新设备设置参数失败");
                return WebResult.failure("发送给阿里更新设备设置参数失败").toMap();
            }
            devParam.setUpdatetime(new Date());
            devParam.setDevparamvalue(paramVal);
            paramService.updateByPrimaryKeySelective(devParam);
            return WebResult.success().toMap();
        } catch (Exception e) {
            LOGGER.error("PubDevSetParam update",e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 删除参数设置
     * @param paramGroupId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "deleteParamGroup", method = RequestMethod.POST)
    public Map<String,Object> deleteParamGroup(Long paramGroupId){
        PubDevConfigParam pubDevConfigParam=configParamService.selectByPrimaryKey(paramGroupId);
        Long adminId = getFactoryAdminId();
        if(pubDevConfigParam.getAdminid()!=null&&!pubDevConfigParam.getAdminid().equals(adminId)){
            return WebResult.failure("您无权限操作此参数").toMap();
        }
        try{
            configParamService.deleteByPrimaryKey(paramGroupId);
            return WebResult.success().info("操作成功!").toMap();
        }catch (Exception e){
            LOGGER.error("PubParamGroup isnert",e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 修改参数组名称
     * @param paramGroupId
     * @param groupName
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "updateParamGroupName", method = RequestMethod.POST)
    public Map<String,Object> updateParamGroupName(
            Long paramGroupId,
            String groupName
    ){
        PubParamGroup pubParamGroup=groupService.selectByPrimaryKey(paramGroupId);
        if(pubParamGroup.getAdminid()!=null&&!pubParamGroup.getAdminid().equals(getAdminId())){
            return WebResult.failure("您无权限操作此参数组").toMap();
        }
        try{
            pubParamGroup.setParamgroupname(groupName);
            groupService.updateByPrimaryKey(pubParamGroup);
            return WebResult.success().info("操作成功!").toMap();
        }catch (Exception e){
            LOGGER.error("PubParamGroup update",e);
            return WebResult.failure(e).toMap();
        }
    }

}
